package com.carl;

import com.carl.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class Context_Creat {
    public static void main(String[] args) throws IOException {
        //创建es客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.73.130", 9200, "http")));


        IndexRequest indexRequest = new IndexRequest();
        indexRequest.index("user").id("1001");

        //创建数据对象
        User user = new User();
        user.setName("张三");
        user.setAge(19);
        user.setSex("男");

        ObjectMapper objectMapper = new ObjectMapper();
        String userJson = objectMapper.writeValueAsString(user);

        //添加文档数据，数据格式为JSON格式
        indexRequest.source(userJson, XContentType.JSON);

        //客户端发送请求，获取响应对象
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);

        //打印结果信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());



        client.close();
    }
}
